package seatiger.tomcat.coyote.http11.filters;

import seatiger.tomcat.coyote.OutputBuffer;
import seatiger.tomcat.coyote.Response;
import seatiger.tomcat.coyote.http11.OutputFilter;
import seatiger.tomcat.util.buf.ByteChunk;

import java.io.IOException;

/**
 * 主要用于 返回的报文头有content-length字段
 */
public class IdentityOutputFilter implements OutputFilter {

    protected int contentLength = -1;

    /**
     * 剩余未写出的字节个数
     */
    protected long remaining = 0;

    /**
     * 下一个执行的buffer
     */
    protected OutputBuffer buffer;

    /**
     * 写出字节
     *
     * @param chunk
     * @param response
     * @return
     * @throws IOException
     */
    @Override
    public int doWrite(ByteChunk chunk, Response response) throws IOException {
        int result = -1;
        if (contentLength >= 0) {
            if (remaining > 0) {
                result = chunk.getLength();
                if (result > remaining) {
                    chunk.setBytes(chunk.getBuff(), chunk.getStart(), (int) remaining);
                    result = (int) remaining;
                    remaining = 0;
                } else {
                    remaining = remaining - result;
                }
                buffer.doWrite(chunk, response);
            } else {
                chunk.recycle();
                result = -1;
            }
        } else {
            buffer.doWrite(chunk, response);
            result = chunk.getLength();
        }
        return result;
    }

    @Override
    public void setResponse(Response response) {
        contentLength = response.getContentLength();
        remaining = contentLength;
    }

    @Override
    public void recycle() {
        contentLength = -1;
        remaining = 0;
    }

    @Override
    public void setBuffer(OutputBuffer buffer) {
        this.buffer = buffer;
    }

    @Override
    public long end() throws IOException {
        if (remaining > 0) {
            return remaining;
        }
        return 0;
    }
}
